﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace RuoVea.OOrgMenuRoleUser.Template.Filters;

/// <summary>
/// 
/// </summary>
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    /// <summary>
    /// 
    /// </summary>
    /// <param name="reader"></param>
    /// <param name="typeToConvert"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        try
        {
            return DateTime.ParseExact(s: reader.GetString(), DateTimeFormat, CultureInfo.InvariantCulture);
        }
        catch {
            try
            {
                return DateTime.ParseExact(s: reader.GetString(), "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
            }
            catch
            {
                try
                {
                    return DateTime.ParseExact(s: reader.GetString(), "yyyy-MM-dd HH", CultureInfo.InvariantCulture);
                }
                catch
                {
                    return DateTime.ParseExact(s: reader.GetString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
            }
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="writer"></param>
    /// <param name="value"></param>
    /// <param name="options"></param>
    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(DateTimeFormat, CultureInfo.InvariantCulture));
    }
}